package com.sip.stream.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import java.lang.reflect.ParameterizedType


abstract class BaseFragment<VB : ViewBinding> : DialogFragment() {

    lateinit var binding: VB

    lateinit var compositeDisposable: CompositeDisposable

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?,
    ): View? {
        binding = getViewBindingForFragment(inflater, container)
        initPage()
        return binding.root
    }

    abstract fun initPage()

    @Suppress("UNCHECKED_CAST")
    fun getViewBindingForFragment(layoutInflater: LayoutInflater, container: ViewGroup?): VB {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        )
        return method.invoke(null, layoutInflater, container, false) as VB
    }

    open fun addDisposable(disposable: Disposable?): Disposable? {
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        compositeDisposable!!.add(disposable!!)
        return disposable
    }

    open fun addDisposableObserver(disposableObserver: DisposableObserver<*>?): DisposableObserver<*>? {
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        compositeDisposable!!.add(disposableObserver!!)
        return disposableObserver
    }
}